package driver.controller;

import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import member.model.MemberService;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import to.DriverTO;
import to.MemberTO;
import driver.model.DriverService;

@Controller
public class DriverController {
	private DriverService dService;
	private MemberService mService;
	public DriverController(DriverService dService, MemberService mService){
		this.dService = dService;
		this.mService = mService;
	}
	
	@RequestMapping("/driver.do")
	public ModelAndView joinDriver(DriverTO dto, MemberTO mto)throws SQLException{
		ModelAndView mv = null;
		try {
			mv = new ModelAndView();
			mto.setMemberType(2);
			mService.modifyMember(mto);
			//dto.setPhone(dService.getMemberByPhone(phone));
			dService.joinDriver(dto);
			mv.setViewName("index.tiles");
		} catch (SQLException e) {
			e.printStackTrace();
			mv = new ModelAndView("member/error.tiles","error_message", e.getMessage());
		}
		return mv;
	}
	
	@RequestMapping("/alldriver.do")
	//전체 회원 목록 조회
	public ModelAndView getDriverList(HttpServletRequest request, HttpServletResponse response){
		ModelAndView mv = null;
		try {
			ArrayList<MemberTO> mList = mService.getMemberList();
			ArrayList<DriverTO> dList = dService.getDriverList();
			request.setAttribute("member_list", mList);
			request.setAttribute("driver_list", dList);
			mv = new ModelAndView("member/member_list.tiles");
		} catch (Exception e) {
			e.printStackTrace();
			mv = new ModelAndView("member/error.tiles", "error_message", e.getMessage());
		}
		return mv;
	}
	
	//회원 탈퇴 처리
		@RequestMapping("/removeDriver.do")
		public ModelAndView removeMember(HttpServletRequest request, HttpServletResponse response, HttpSession session){
			DriverTO loginInfo = (DriverTO)session.getAttribute("login_info");
			ModelAndView mv = null;
			if(loginInfo == null){//로그인 안된 경우
				mv = new ModelAndView("member/login_form.tiles", "error_message", "로그인 후 탈퇴가 가능합니다. 로그인 먼저 하세요");
			}else{
				try {
					dService.removeDriverByPhone(loginInfo.getPhone());
					mv = new ModelAndView("member/login_form.tiles");
					//세션 소멸시키기
					session.invalidate();
				}catch (SQLException e) {
					e.printStackTrace();
					mv = new ModelAndView("member/error.tiles", "error_message", e.getMessage());
				}
			}
			return mv;
		}
}
